package cn.com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    private ServerSocket serverSocket;

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    public Server(){

        try {
            serverSocket = new ServerSocket(8080);
            System.out.println("与客户端建立连接");
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public void start(){

        try{
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");

                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t = new Thread(clientHandler);
                t.start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private class ClientHandler implements Runnable{

        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }


        @Override
        public void run() {
            try{

                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                String message = null;
                while ((message = br.readLine())!=null){
                    System.out.println("客户端说: " + message);
                }

            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
